package com.example.demo;


import com.alibaba.fastjson.JSON;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;

import java.io.IOException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;

@ControllerAdvice
public class RequestAdvice implements RequestBodyAdvice {

    @Override
    public boolean supports(MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    //读取参数前执行
    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) throws IOException {
        return httpInputMessage;
    }

    //读取参数后执行
    @Override
    public Object afterBodyRead(Object o, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        /*System.out.println("读取参数后执行开始");
        Method method=methodParameter.getMethod();
        System.out.println("method="+method.getDeclaringClass().getSimpleName());
        System.out.println("name="+method.getName());
        System.out.println("data="+JSON.toJSONString(o));
        System.out.println("读取参数后执行结束");*/
        return o;
    }

    //无请求时的处理
    @Override
    public Object handleEmptyBody(Object o, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
       /* System.out.println("无请求开始");
        Method method=methodParameter.getMethod();
        System.out.println("method="+method.getDeclaringClass().getSimpleName());
        System.out.println("name="+method.getName());
        System.out.println("无请求结束");*/
        return o;
    }

}
